<template>
  <el-dialog
    v-model="dialogVisible"
    :title="dialogTitle"
    :width="700"
    :append-to-body="false"
    :close-on-click-modal="false"
    @close="handleClose"
    custom-class="center-detail"
  >
    <JLForm
      ref="formRef"
      :form-config="formConfig"
      :form-data="formData"
      :form-item-config="formItemConfig"
    >
      <template #slotOrganize>
        <el-tree-select
          collapse-tags
          collapse-tags-tooltip
          v-model="formData.organizeName"
          :data="treeData"
          show-checkbox
          check-strictly
          :props="{ label: 'orgName' }"
          node-key="orgCode"
          ref="treeSelectRef"
          :default-expand-all="true"
        />
      </template>
      <template #slotAddress>
        <Address v-model="formData.address"></Address>
      </template>
    </JLForm>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button color="#0560FD" type="primary" @click="submit">确定</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import {
  updateProject,
  getGroupByAppId,
  getOrganizationTree,
  getLicensedFirstCompany,
  addProject,
} from '@/api/project/index';
import Address from '@/components/address/index.vue';
import { JLForm } from '@jl/element-plus';
import { ref } from 'vue';
import { create } from './composables/create';
import { el } from 'element-plus/es/locale';
import { messageUtil } from '@jl/element-plus/utils';

defineOptions({
  name: '',
});
const { filedStatus, formRef, formConfig, formData, formItemConfig } = create();

interface IProps {
  project: any;
}
const props = withDefaults(defineProps<IProps>(), {
  project: null,
});

// 作用：记录编辑时，项目名称和项目code是否改变
let backupData: any = null;

const dialogVisible = ref<boolean>(true);
const dialogTitle = ref<string>('新增项目');
const emit = defineEmits(['closeHandle']);
const groupList = ref<any>([]);
const orgList = ref<any>([]);
const org = ref<any>();
const appId = process.env.VUE_APP_ID;

onMounted(() => {
  if (appId) {
    // getGroupByAppId({ appId }).then((res: any) => {
    //   groupList.value = res;
    // });
    getLicensedFirstCompany().then((res: any) => {
      groupList.value = [res];
    });
    getOrganizationTree({ appId }).then((res: any) => {
      orgList.value = res;
    });
  }
  if (props.project) {
    backupData = {
      projectCode: props.project.projectCode,
      projectName: props.project.projectName,
    };
    formData.value = {
      id: props.project.id,
      projectCode: props.project?.projectCode,
      projectName: props.project?.projectName,
      projectId: props.project.id,
      organizeName: props.project.orgCode ?? props.project.companyCode + '+company',
      province: props.project.provinceName,
      city: props.project.cityName,
      district: props.project.areaName,
      address: [props.project.provinceName, props.project.cityName, props.project.areaName],
    };
    dialogTitle.value = '编辑项目';
  }
});

const treeData = computed(() => {
  const data =
    groupList.value?.map((group: any) => ({
      orgName: group.companyName,
      orgCode: group.companyCode + '+company',
      id: group.id,
      data: group,
      type: 'company',
      children: orgList.value?.rows
        ? JSON.parse(JSON.stringify(orgList.value?.rows))
            ?.filter((org: any) => org.companyCode === group.companyCode && org.appId === appId)
            .map((el: any) => ({ ...el, parentCode: el.companyCode }))
        : undefined,
    })) ?? [];
  return data;
});

function handleClose() {
  emit('closeHandle');
}

function submit() {
  formRef.value?.getInstance().validate((valid, fields) => {
    if (valid) {
      if (props.project) {
        deal('update');
      } else {
        deal('');
      }
    }
  });
}

function deal(type: string) {
  const data: any = {
    ...formData.value,
    provinceName: formData.value.address[0],
    cityName: formData.value.address[1],
    areaName: formData.value.address[2],
    status: 1,
  };
  const arr = formData.value.organizeName.split('+');
  if (arr[1]) {
    data.companyCode = arr[0];
    data.orgCode = null;
  } else {
    // function findParent(data: any, id: any, result: any) {
    //   for (let item of data) {
    //     if (item.orgCode === id) {
    //       result.unshift(item.orgCode);
    //       return true;
    //     }
    //     if (item.children && item.children.length > 0) {
    //       let isFind = findParent(item.children, id, result);
    //       if (isFind) {
    //         result.unshift(item.orgCode);
    //         return true;
    //       }
    //     }
    //   }
    //   return false;
    // }
    // const result: any = [];
    // findParent(treeData.value, arr[0], result);
    // data.companyCode = result[0].split('+')[0];
    data.companyCode = groupList.value[0].companyCode;
    data.orgCode = arr[0];
  }
  delete data.address;
  if (type === 'update') {
    try {
      updateProject({ ...props.project, ...data }).then(async (res: any) => {
        filedStatus.projectCodeRepetition = !!res?.projectCodeRepetition;
        filedStatus.projectNameRepetition = !!res?.projectNameRepetition;
        formRef.value?.getInstance().validate((valid, fields) => {
          filedStatus.projectCodeRepetition = false;
          filedStatus.projectNameRepetition = false;
          if (valid) {
            messageUtil.success('操作成功');
            handleClose();
          }
        });
      });
    } catch (error) {}
  } else {
    addProject(data).then((res: any) => {
      messageUtil.success('操作成功');
      handleClose();
    });
  }
}
</script>

<style lang="less" scoped></style>
